import 'dart:io';

import 'package:flutter/material.dart';
import 'package:reorderables/reorderables.dart';
import 'package:xws/helpers/safe_state.dart';
import 'package:xws/utils/theme_util.dart';
import 'package:xws/utils/tools_util.dart';
import 'package:xws/widgets/app_btn.dart';
import 'package:xws/widgets/app_img.dart';
import 'package:xws/widgets/video_box.dart';

/// 选择图片和视频
class SelectImagesVideo extends StatefulWidget {
  const SelectImagesVideo({
    Key? key,
    this.initImages,
    this.maxCount = 9,
    this.initVideoPath,
    this.onImgChanged,
    this.onVideoChanged,
  }) : super(key: key);

  @override
  _SelectImagesVideoState createState() => _SelectImagesVideoState();

  final List<String>? initImages;

  final String? initVideoPath;

  final Function(List<String>)? onImgChanged;
  final Function(String?)? onVideoChanged;

  final int maxCount;
}

class _SelectImagesVideoState extends State<SelectImagesVideo> with SafeState<SelectImagesVideo> {
  final List<String> _images = <String>[];

  final double _itemSize = (sw - 60) / 3 - 0.6;

  final GlobalKey<_AddVideoState> _videoKey = GlobalKey<_AddVideoState>();

  /// 图片总数
  int get _total => _images.length;

  @override
  void initState() {
    super.initState();
    if (widget.initImages != null && widget.initImages!.isNotEmpty) {
      _images.addAll(widget.initImages!);
    }
  }

  /// 预览
  Future<void> _preView(int index, String tag) async {
    await assetsViewer(context, _images, initIndex: index, heroTag: tag);
  }

  /// 选择图片
  Future<void> _pickImages() async {
    final List<String>? imgs = await pickImgs(context, max: widget.maxCount - _images.length);
    if (imgs != null && imgs.isNotEmpty) {
      safeSetState(() => _images.addAll(imgs));
      widget.onImgChanged?.call(_images);
    }
  }

  /// 移除图片
  Future<void> _removeImg(int index) async {
    _images.removeAt(index);
    widget.onImgChanged?.call(_images);
    safeSetState(() {});
  }

  @override
  Widget build(BuildContext context) {
    final int lastRowCount = _images.length % 3;

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        _buildImgList,
        if (lastRowCount == 2) const SizedBox(height: 10),
        if (lastRowCount == 2)
          _AddVideo(
            key: _videoKey,
            initPath: widget.initVideoPath,
            onVideoChanged: widget.onVideoChanged,
          ),
      ],
    );
  }

  /// 图片列表
  Widget get _buildImgList {
    return ReorderableWrap(
      spacing: 10,
      runSpacing: 10,
      onReorder: (int oldIndex, int newIndex) {
        safeSetState(() {
          final String temp = _images[oldIndex];
          _images.removeAt(oldIndex);
          _images.insert(newIndex, temp);
        });
        widget.onImgChanged?.call(_images);
      },
      children: List<Widget>.generate(_total, (int index) {
        if (index >= widget.maxCount) return const SizedBox.shrink();

        if (index == _images.length) return _buildAddBtn;

        return _buildImg(index);
      }),
      footer: _footer,
    );
  }

  Widget? get _footer {
    final int lastRowCount = _images.length % 3;
    if (lastRowCount == 0 || lastRowCount == 1) {
      return Wrap(
        spacing: 10,
        runSpacing: 10,
        children: <Widget>[
          if (_total != widget.maxCount) _buildAddBtn,
          _AddVideo(
            key: _videoKey,
            initPath: widget.initVideoPath,
            onVideoChanged: widget.onVideoChanged,
          ),
        ],
      );
    }

    return _total == widget.maxCount ? null : _buildAddBtn;
  }

  /// 构建图片
  Widget _buildImg(int index) {
    const String tag = 'push_';

    return InkWell(
      onTap: () async => await _preView(index, tag),
      child: Stack(
        alignment: Alignment.topRight,
        children: <Widget>[
          AppImg.fitCover(
            heroTag: tag + index.toString(),
            url: _images[index],
            radius: 4,
            width: _itemSize,
            height: _itemSize,
          ),
          AppBtn(
            onTap: () async => await _removeImg(index),
            padding: const EdgeInsets.all(4),
            color: red(context),
            child: Icon(
              Icons.close_rounded,
              size: 14,
              color: white(context),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建添加图片按钮
  Widget get _buildAddBtn {
    return AppBtn(
      width: _itemSize,
      height: _itemSize,
      color: canvas(context),
      onTap: _pickImages,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Icon(
            Icons.add_photo_alternate_rounded,
            size: 50,
            color: disable(context).withOpacity(0.1),
          ),
          Text(
            '添加图片',
            style: TextStyle(
              fontSize: 11,
              color: disable(context),
            ),
          ),
        ],
      ),
    );
  }
}

/// 添加视频
class _AddVideo extends StatefulWidget {
  const _AddVideo({Key? key, this.initPath, this.onVideoChanged}) : super(key: key);

  @override
  _AddVideoState createState() => _AddVideoState();

  final String? initPath;

  final Function(String?)? onVideoChanged;
}

class _AddVideoState extends State<_AddVideo> with SafeState<_AddVideo> {
  String? _video;

  final double _itemSize = (sw - 60) / 3 - 0.6;

  @override
  void initState() {
    super.initState();
    if (widget.initPath != null && widget.initPath!.isNotEmpty) {
      _video = widget.initPath;
    }
  }

  /// 添加视频
  Future<void> _pickVideo() async {
    final String? v = await pickVideo(context);
    if (v != null) {
      safeSetState(() => _video = v);
      widget.onVideoChanged?.call(v);
    }
  }

  /// 移除视频
  Future<void> _remove() async {
    if (_video != null) {
      if (_video!.startsWith('/')) {
        final File f = File(_video!);
        if (f.existsSync()) f.deleteSync();
      }

      safeSetState(() => _video = null);
      widget.onVideoChanged?.call(null);
    }
  }

  @override
  Widget build(BuildContext context) {
    return _video == null ? _buildAddVideoBtn : _buildVideo;
  }

  /// 构建视频
  Widget get _buildVideo {
    return Stack(
      alignment: Alignment.topRight,
      children: <Widget>[
        VideoBox(
          path: _video!,
          width: _itemSize,
          height: _itemSize,
          imageFit: BoxFit.cover,
        ),
        AppBtn(
          onTap: () async => await _remove(),
          padding: const EdgeInsets.all(4),
          color: red(context),
          child: Icon(
            Icons.close_rounded,
            size: 14,
            color: white(context),
          ),
        ),
      ],
    );
  }

  /// 构建添加视频按钮
  Widget get _buildAddVideoBtn {
    return AppBtn(
      color: canvas(context),
      width: _itemSize,
      height: _itemSize,
      onTap: _pickVideo,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Icon(
            Icons.video_call_rounded,
            size: 50,
            color: disable(context).withOpacity(0.1),
          ),
          Text(
            '录制视频',
            style: TextStyle(
              fontSize: 11,
              color: disable(context),
            ),
          ),
        ],
      ),
    );
  }
}
